package wallet

import (
	"errors"

	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
)

// RechargeRecord 用户充值表
type RechargeRecord struct {
	gorm.Model
	UserID         int64 `json:"userid" gorm:"column:userid;type:int(11);comment:用户ID"`
	RechargeAmount int64 `json:"recharge_amount" gorm:"column:recharge_amount;type:int(11);comment:充值金额"`
	BonusAmount    int64 `json:"bonus_amount" gorm:"column:bonus_amount;type:int(11);comment:赠送金额"`
}

type RechargeRecordDescription struct {
	gorm.Model
	UserID          int64  `json:"userid" gorm:"column:userid;type:int(11);comment:用户ID"`
	RechargeAmount  int64  `json:"recharge_amount" gorm:"column:recharge_amount;type:int(11);comment:充值金额"`
	BonusAmount     int64  `json:"bonus_amount" gorm:"column:bonus_amount;type:int(11);comment:赠送金额"`
	TransactionType string `json:"transaction_type" gorm:"column:transaction_type;type:varchar(20);comment:交易类型: recharge/consume/refund"`
	Description     string `json:"description" gorm:"column:description;type:varchar(255);comment:交易描述"`
}

func (r *RechargeRecord) CreatAmount(transactionType, description string, amount, balance float64) (rech *RechargeRecordDescription, err error) {
	return rech, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Transaction(func(tx *gorm.DB) error {
			// 创建充值记录
			if err = tx.Create(r).Error; err != nil {
				return err
			}

			var b UserBalance
			firstBalance, err := b.FirstBalance(r.UserID)
			if err != nil {
				if errors.Is(err, gorm.ErrRecordNotFound) {
					if firstBalance.ID == 0 {
						if err = tx.Create(&UserBalance{
							UserID:  r.UserID,
							Balance: b.Balance,
						}).Error; err != nil {
							return err
						}

						if err = tx.Create(&UserConsumptionDetails{
							UserID:          r.UserID,
							TransactionType: transactionType,
							Amount:          amount,
							Balance:         balance,
							Description:     description,
						}).Error; err != nil {
							return err
						}
					}
					return err
				}
				return err
			}

			if firstBalance.Balance < -float64(r.RechargeAmount) {
				return errors.New("余额不足")
			}

			if err = tx.Model(&UserBalance{}).Where("userid = ?", r.UserID).Update("balance", gorm.Expr("balance+?", r.RechargeAmount+r.BonusAmount)).Error; err != nil {
				return err
			}

			a := &UserConsumptionDetails{
				UserID:          r.UserID,
				TransactionType: transactionType,
				Amount:          float64(r.RechargeAmount),
				Balance:         float64(r.BonusAmount),
				Description:     description,
			}

			if err = tx.Create(&a).Error; err != nil {
				return err
			}

			rech = &RechargeRecordDescription{
				UserID:          r.UserID,
				RechargeAmount:  r.RechargeAmount,
				BonusAmount:     r.BonusAmount,
				TransactionType: a.TransactionType,
				Description:     a.Description,
			}
			return nil
		})
	})
}
